package com.cff.shorturl.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class Utils {
	public static Properties loadPropertiesFile(String fullFile) {
		Properties config = null;
		try {
			InputStream inputStream = Utils.class.getClassLoader().getResourceAsStream(fullFile);
			config = new Properties();
			config.load(inputStream);
			inputStream.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return config;
	}
	
	/**
	 * 获取classpath下的文件
	 * 
	 * @param path
	 * @return
	 * @throws IOException 
	 */
	public static String getFile(String path) throws IOException {
		System.out.println("访问路径："+path);
		if(path.startsWith("/"))path = path.substring(1);
		InputStream in = Utils.class.getClassLoader().getResourceAsStream(path);
		if (in == null) {
			in = Utils.class.getClassLoader().getResourceAsStream("resources/" + path);
		}
		if(in == null){
			throw new IOException("该资源不存在！");
		}
		String usage = "";
		if(path.endsWith(".html")){
			usage = readHtml(in);
		}else{
			usage = readToString(in);
		}

		in.close();
		return usage;
	}
	
	public static String readHtml(InputStream in) throws IOException {
		InputStreamReader reader = new InputStreamReader(in,"UTF-8");//定义一个fileReader对象，用来初始化BufferedReader
        BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象，将文件内容读取到缓存
        StringBuilder sb = new StringBuilder();//定义一个字符串缓存，将字符串存放缓存中
        String s = "";
        while ((s =bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
            sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
        }
        bReader.close();
        String str = sb.toString();
        return str;
    }
	
	public static String readToString(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toString("UTF-8");
	}
}
